package com.sptpc.learnspring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource crosConfigurationSource
                = new UrlBasedCorsConfigurationSource();
        // 添加映射路径
        crosConfigurationSource.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(crosConfigurationSource);
    }

    // 添加跨域配置
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 放行所有原始域
        corsConfiguration.addAllowedOrigin("*");
        // 放行所有原始请求header
        corsConfiguration.addAllowedHeader("*");
        // 暴露所有原始请求header
        corsConfiguration.addExposedHeader("*");
        // 放行所有原始请求方法
        corsConfiguration.addAllowedMethod("*");
        // 发送原理的cookie
        corsConfiguration.setAllowCredentials(true);
        // 不用再次发起预检请求的时间
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
}
